package handler

import (
	"net/http"

	"github.com/gin-gonic/gin"

	"plastic-company/internal/model"
)

// GetNews 获取所有新闻
func GetNews(c *gin.Context) {
	var news []model.News
	result := db.Find(&news)

	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, model.APIResponse{
			Success: false,
			Message: "获取新闻失败",
		})
		return
	}

	c.JSON(http.StatusOK, model.APIResponse{
		Success: true,
		Data:    news,
	})
}

// GetNewsByID 获取单个新闻
func GetNewsByID(c *gin.Context) {
	id := c.Param("id")

	var news model.News
	result := db.First(&news, id)

	if result.Error != nil {
		if result.Error.Error() == "record not found" {
			c.JSON(http.StatusNotFound, model.APIResponse{
				Success: false,
				Message: "新闻不存在",
			})
		} else {
			c.JSON(http.StatusInternalServerError, model.APIResponse{
				Success: false,
				Message: "获取新闻失败",
			})
		}
		return
	}

	c.JSON(http.StatusOK, model.APIResponse{
		Success: true,
		Data:    news,
	})
}

// CreateNews 创建新闻
func CreateNews(c *gin.Context) {
	var news model.News

	if err := c.ShouldBindJSON(&news); err != nil {
		c.JSON(http.StatusBadRequest, model.APIResponse{
			Success: false,
			Message: "请求参数错误",
		})
		return
	}

	result := db.Create(&news)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, model.APIResponse{
			Success: false,
			Message: "创建新闻失败",
		})
		return
	}

	c.JSON(http.StatusCreated, model.APIResponse{
		Success: true,
		Message: "创建新闻成功",
		Data:    news,
	})
}

// UpdateNews 更新新闻
func UpdateNews(c *gin.Context) {
	id := c.Param("id")

	var news model.News
	if err := c.ShouldBindJSON(&news); err != nil {
		c.JSON(http.StatusBadRequest, model.APIResponse{
			Success: false,
			Message: "请求参数错误",
		})
		return
	}

	result := db.Model(&news).Where("id = ?", id).Updates(&news)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, model.APIResponse{
			Success: false,
			Message: "更新新闻失败",
		})
		return
	}

	c.JSON(http.StatusOK, model.APIResponse{
		Success: true,
		Message: "更新新闻成功",
		Data:    news,
	})
}

// DeleteNews 删除新闻
func DeleteNews(c *gin.Context) {
	id := c.Param("id")

	result := db.Delete(&model.News{}, id)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, model.APIResponse{
			Success: false,
			Message: "删除新闻失败",
		})
		return
	}

	c.JSON(http.StatusOK, model.APIResponse{
		Success: true,
		Message: "删除新闻成功",
	})
}